package com.sikaryofficial.qrcode.controller;

import cn.hutool.core.util.StrUtil;
import com.sikaryofficial.common.core.utils.ip.IpUtils;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.qrcode.config.QrcodeRedirectConfig;
import com.sikaryofficial.qrcode.constant.BrandNoEnum;
import com.sikaryofficial.qrcode.manager.QrSkeCallbackManager;
import com.sikaryofficial.qrcode.service.brand.cache.BrandTasteCacheService;
import com.sikaryofficial.system.api.model.product.BrandTasteDTO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc : 重定向服务
 * @date : 2025/03/22 16:08
 */
@RestController
@RequestMapping("/redirect")
@Api(tags = "重定向服务")
@Slf4j
public class RedirectController {
    @Autowired
    private BrandTasteCacheService brandTasteCacheService;
    @Resource
    private QrcodeRedirectConfig redirectConfig;
    @Autowired
    private QrSkeCallbackManager qrSkeCallbackManager;
    @GetMapping("/byParam")
    public void handleRedirect(@RequestParam String p, @RequestParam String e,
                               @RequestHeader(value = "User-Agent", required = false) String userAgent,
                               HttpServletResponse response) throws IOException {
        // 根据 p 和 e 参数进行逻辑判断
        log.info("处理重定向请求, 参数 p: {}, 参数 e: {}", p, e);
        // ✅ 无论参数是否正确，都记录访问信息
        qrSkeCallbackManager.callbackForUserDetail(IpUtils.getIpAddr(), p, SecurityUtils.getUserId(), userAgent);
        if (isValidParameters(e)) {
            BrandTasteDTO brandTasteDTO = brandTasteCacheService.getProductByParam(p);
            if (Objects.isNull(brandTasteDTO) || StrUtil.isBlank(brandTasteDTO.getBrandNo())) {
                log.error("获取产品信息失败");
                redirect(response);
                return;
            }
            log.info("获取产品信息 brandNo: {}, BrandTasteId: {}", brandTasteDTO.getBrandNo(), brandTasteDTO.getBrandTasteId());
            BrandNoEnum brandNoEnum = BrandNoEnum.getByCode(brandTasteDTO.getBrandNo());
            redirect(response, brandNoEnum.getCode().toUpperCase(Locale.ROOT), p);
        } else {
            redirect(response);
        }
    }

    private void redirect(HttpServletResponse response) throws IOException {
        redirect(response, BrandNoEnum.COUNTERFEIT_BRAND.getCode());
    }

    private void redirect(HttpServletResponse response, String brandCode) throws IOException {
        redirect(response, brandCode, null);
    }

    private void redirect(HttpServletResponse response, String brandCode, String param) throws IOException {
        String url = param == null ? redirectConfig.getBrandUrl(brandCode) : redirectConfig.getBrandUrl(brandCode, param);
        if (url != null) {
            response.sendRedirect(url);
        } else {
            log.error("未找到对应的重定向 URL, brandCode: {}", brandCode);
            response.sendRedirect(redirectConfig.getBrandUrl(BrandNoEnum.COUNTERFEIT_BRAND.getCode()));
        }
    }

    private boolean isValidParameters(String e) {
        // 示例逻辑：检查 p 是否符合特定格式（如 517-1-a7a1-bc20）
        return "1".equals(e);
    }
}
